# -*- coding: utf-8 -*-

#
# peerscape.http.controllers.person
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors:
#       Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement

import cgi
from webob import Response
from webob.exc import HTTPMovedPermanently, HTTPTemporaryRedirect
from peerscape.http.controllers import BaseController
from peerscape.core.policy import Unauthorized
from peerscape import VERSION
from peerscape.daemon import register
from peerscape.sync import report_sync_sessions
from peerscape.profile.application import autoinstantiate
from peerscape.db.util import get_timestamp

class Person(BaseController):
    def index(self, req):
        # check the type before proceeding
        redir_url = self.require_type(req, ['principal'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('person.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']
            v['is_empty'] = False

            v['recovery_code'] = None
            if v['is_self']:
                escrow_info = db.get_escrow_info(v['my_iid'])
                if escrow_info:
                    v['recovery_code'] = escrow_info['code']

                # service any auto instantiation requests
                autoinstantiate(db)

            v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])
            v['friend_list'] = self.process_friend_list(db, v['hexlabel'], v['my_iid'], name_sort=False)
            v['group_list'] = self.process_group_links_list(db, v['hexlabel'], v['my_iid'])
            v['events_list'] = self.process_events_list(db, v['hexlabel'], v['my_iid'])
            v['status_list'] = self.process_status_list(db, v['hexlabel'], limit=4)
            v['atom_list'] = self.process_atom_list(db, v['hexlabel'], limit=4)
            v['content_list'] = self.process_content_list(db, v['hexlabel'])
            v['invitations'] = self.get_invitations(db)
            v['is_friend'] = v['friend_list']['items'].has_key(db.get_my_iid())
            v['is_invitation_pending'] = self.is_invitation_pending(db, v['hexlabel'])
            v['directory_url'] = 'http://%s.hexlabel.net/' % register.IID
            v['sync_sessions'] = report_sync_sessions()
            v['errors'] = False
            v['message'] = ''
            v['errors_pending'] = False
            v['message_pending'] = ''

            # test for version update prompt
            if db.is_upgrade_recommended():
                v['upgrade_recommended'] = True
                v['current_version'] = VERSION
                v['recommended_version'] = db.get_recommended_version()
            else:
                v['upgrade_recommended'] = False
                v['current_version'] = VERSION
                v['recommended_version'] = VERSION

            # test for empty profile
            if v['profile_fields']['personal']['meta']['num_visible'] == 0 and \
            v['profile_fields']['location']['meta']['num_visible'] == 0 and \
            v['profile_fields']['contact']['meta']['num_visible'] == 0 and \
            not v['profile_fields']['generic']['about']['values'][0]['value']:
                    v['is_empty'] = True


            if req.POST.has_key('invitation_accept'):
                if req.method == 'POST':
                    if req.POST.has_key('invitation_iid') and req.POST['invitation_iid']:
                        v['iid'] = req.POST['invitation_iid']
                        if self.is_invitation_pending(db, v['my_iid'], v['iid']):
                            result = self.accept_invitation(db, v['iid'])
                            self.delete_invitation(db, v['iid'])
                            if result == 'OK':
                                # ACCEPT
                                if db.get_dataset_type(v['iid']) == 'group':
                                    # add a private link when join a group
                                    db.add_link(v['my_iid'], v['iid'])

                                v['errors_pending'] = False
                                v['message_friends'] = _('Invitation accepted')
                                v['invitations'] = self.get_invitations(db)
                                v['friend_list'] = self.process_friend_list(db, v['my_iid'])
                                v['group_list'] = self.process_group_links_list(db, v['my_iid'])

                                # redirect to profile
                                redir_url = str('http://%s.hexlabel.net/' % v['iid'])
                                return HTTPMovedPermanently(location=redir_url)
                            else:
                                # ERROR could not accept
                                v['invitations'] = self.get_invitations(db)
                                v['errors_pending'] = True
                                v['message_pending'] = _(result)
                                return view.render(**v)

                        else:
                            # ERROR no such invitation
                            v['invitations'] = self.get_invitations(db)
                            v['errors_pending'] = True
                            v['message_pending'] = _('No such invitation')
                            return view.render(**v)
                    else:
                        # ERROR no iid
                        v['invitations'] = self.get_invitations(db)
                        v['errors_pending'] = True
                        v['message_pending'] = _('No iid given')
                        return view.render(**v)
                else:
                    # ERROR not post
                    pass
                                

            if req.POST.has_key('invitation_decline'):
                if req.method == 'POST':
                    if req.POST.has_key('invitation_iid') and req.POST['invitation_iid']:
                        v['iid'] = req.POST['invitation_iid']
                        if self.is_invitation_pending(db, v['my_iid'], v['iid']):
                            # DECLINE
                            self.delete_invitation(db, v['iid'])
                            v['invitations'] = self.get_invitations(db)
                            v['errors_pending'] = False
                            v['message_pending'] = _('Invitation declined')
                            return view.render(**v)

                        else:
                            # ERROR no such invitation
                            v['invitations'] = self.get_invitations(db)
                            v['errors_pending'] = True
                            v['message_pending'] = _('No such invitation')
                            return view.render(**v)
                    else:
                        # ERROR no iid
                        v['invitations'] = self.get_invitations(db)
                        v['errors_pending'] = True
                        v['message_pending'] = _('No iid given')
                        return view.render(**v)
                else:
                    # ERROR not post
                    pass

            if req.params.has_key('entercode'):
                # deal with invite code entry
                if req.params.has_key('invitecode') and req.params['invitecode']:
                    v['invitecode'] = req.params['invitecode'].strip()
                    try:
                        inviter = db.fetch_invitation_and_make_pending(v['invitecode'])
                        invitation = self.get_invitation(db, inviter, force_refresh=True)
                        assert invitation
                    except LookupError:
                        v['invitations'] = self.get_invitations(db)
                        v['errors'] = True
                        v['message'] = _('Invalid invitation code. Note: invitation codes are valid for a week and can only be used once.')
                        return view.render(**v)
                    except:
                        v['invitations'] = self.get_invitations(db)
                        v['errors'] = True
                        v['message'] = _('Error fetching invitation.')
                        return view.render(**v)
        
                    if invitation['iid'] == db.get_my_iid():
                        self.delete_invitation(db, invitation['iid'])
                        v['invitations'] = self.get_invitations(db)
                        v['errors'] = True
                        v['message'] = _('Invitation code was created by you and has now been removed.')
                        return view.render(**v)

                    elif v['friend_list']['items'].has_key(invitation['iid']):
                        self.delete_invitation(db, invitation['iid'])
                        v['invitations'] = self.get_invitations(db)
                        v['errors'] = True
                        v['message'] = _('This person (%s) is already your friend' % (v['friend_list']['items'][invitation['iid']]['name']))
                        return view.render(**v)
        
                    else:
                        self._expand_invitations_rep(db)
                        db.subscribe(invitation['iid'])

                        # redirect to inviter profile
                        redir_url = 'http://%s.hexlabel.net/' % invitation['iid']
                        return HTTPMovedPermanently(location=redir_url)

                else:
                    v['invitations'] = self.get_invitations(db)
                    v['invitecode'] = ''
                    v['errors'] = True
                    v['message'] = _('Please enter an invitation code')
                    
                    return view.render(**v)

            v['invitations'] = self.get_invitations(db)
            v['errors'] = False
            v['message'] = ''

            return view.render(**v)
        else:
            return None


    def invite_peerscape_person(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']
            
            if not v['is_self']:
                db.invite_friend(v['hexlabel'])

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)
        else:
            return None


    def edit_status(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']

            if req.POST.has_key('other:0:status'):
                # save new status (always public)
                status = req.POST.get('other:0:status')
                if status and len(status) > 160:
                    status = status[:160]

                status_timestamp = get_timestamp()

                info = db.get_personal_info(v['hexlabel'])
                info.set_field('other', 'status', status, public=True)
                info.set_field('other', 'status_timestamp', status_timestamp, public=True)

                # write profile
                db.set_personal_info(v['hexlabel'], info, status)

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('person.edit_status.html')

            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)

                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['is_self'] = v['my_iid'] == v['hexlabel']
                v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None


    def edit_picture(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']

            if req.POST.has_key('action'):
                if req.POST['action'] == 'delete':
                    # delete picture
                    db.clear_profile_picture(v['hexlabel'])

            if req.POST.has_key('generic:0:picture'):
                # save new picture
                upload = req.POST['generic:0:picture']
                if upload.__class__ == cgi.FieldStorage:
                    with upload.file as f:
                        newpic = f.read()

                    db.set_profile_picture(v['hexlabel'], newpic)

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('person.edit_picture.html')

            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)

                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['is_self'] = v['my_iid'] == v['hexlabel']
                v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None


    def edit(self, req):
        if req.method == 'POST':
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']

            # get the public flags
            public_selectors = set([(key,val) for key,val in req.POST.items() if key.startswith('_public')])

            # get the generic fields
            generic_fields = set([(key,val) for key,val in req.POST.items() if key.startswith('generic')])

            # get the other profile fields
            profile_fields = set(req.POST.items()) - generic_fields - public_selectors

            public_selectors = dict(public_selectors)
            generic_fields = dict(generic_fields)
            profile_fields = dict(profile_fields)

            # update name
            name = (generic_fields['generic:0:name'] or '').strip()
            if name:
                db.set_profile_name(v['hexlabel'], name)

            # update about
            if public_selectors.has_key('_public_generic:0:about'):
                db.set_profile_text(v['hexlabel'], generic_fields['generic:0:about'] or '', public=True)
            else:
                db.set_profile_text(v['hexlabel'], generic_fields['generic:0:about'] or '', public=False)

            # write other fields
            info = db.get_personal_info(v['hexlabel'])
            for key,val in profile_fields.items():
                try:
                    section, n, field = key.split(':')
                    is_public = public_selectors.has_key('_public_%s' % key)

                    # special case for gender
                    if (section == 'personal' and field == 'gender'):
                        if not (val in ('Male', 'Female')):
                            val = ''

                    if (val):
                        info.set_field(section, field, val, public=is_public)
                    else:
                        info.set_field(section, field, '', public=False)

                except:
                    pass

            # write profile
            db.set_personal_info(v['hexlabel'], info)

            # redirect to profile
            redir_url = '/person/'
            return HTTPMovedPermanently(location=redir_url)

        else:
            # GET
            view = self.load_view('person.edit.html')

            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)

                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['my_iid'] = db.get_my_iid()
                v['is_self'] = v['my_iid'] == v['hexlabel']
                v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])

                # engage -->
                return view.render(**v)
            else:
                return None

    def updates(self, req):
        # check the type before proceeding
        redir_url = self.require_type(req, ['principal'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('person.updates.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            # test for version update prompt
            if db.is_upgrade_recommended():
                v['upgrade_recommended'] = True
                v['current_version'] = VERSION
                v['recommended_version'] = db.get_recommended_version()
            else:
                v['upgrade_recommended'] = False
                v['current_version'] = VERSION
                v['recommended_version'] = VERSION

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']
            v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])
            v['events_list'] = self.process_events_list(db, v['hexlabel'], v['my_iid'])
            v['status_list'] = self.process_status_list(db, v['hexlabel'])
            v['atom_list'] = self.process_atom_list(db, v['hexlabel'])
            v['friend_list'] = self.process_friend_list(db, v['hexlabel'], v['my_iid'])
            v['is_friend'] = v['friend_list']['items'].has_key(db.get_my_iid())
            v['sync_sessions'] = report_sync_sessions()

            v['invitations'] = self.get_invitations(db)
            v['errors'] = False
            v['message'] = ''

            return view.render(**v)
        else:
            return None

    def friends(self, req):
        # check the type before proceeding
        redir_url = self.require_type(req, ['principal'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('person.friends.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)

            # test for version update prompt
            if db.is_upgrade_recommended():
                v['upgrade_recommended'] = True
                v['current_version'] = VERSION
                v['recommended_version'] = db.get_recommended_version()
            else:
                v['upgrade_recommended'] = False
                v['current_version'] = VERSION
                v['recommended_version'] = VERSION

            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            v['my_iid'] = db.get_my_iid()
            v['is_self'] = v['my_iid'] == v['hexlabel']
            v['profile_fields'] = self.process_person_profile(db, v['hexlabel'])
            v['friend_list'] = self.process_friend_list(db, v['hexlabel'], v['my_iid'], name_sort=True)
            v['is_friend'] = v['friend_list']['items'].has_key(db.get_my_iid())
            v['sync_sessions'] = report_sync_sessions()

            v['invitations'] = self.get_invitations(db)
            v['errors'] = False
            v['message'] = ''

            return view.render(**v)
        else:
            return None

